package com.kevin.Code.Array;

/**
 * @author Vinlee Xiao
 * @Classname RemoveDuplicatesFromSortedArrayii
 * @Description Leetcode 80. 删除有序数组中的重复项 II 中等难度 有思路
 * @Date 2021/10/29 20:36
 * @Version 1.0
 */
public class RemoveDuplicatesFromSortedArrayii {

    /**
     * @param nums
     * @return
     */
    public int removeDuplicates(int[] nums) {

        int len = nums.length;

        //用于记录数组中中数的个数
        int cntRange = len;

        if (len == 1) {
            return 1;
        }

        for (int i = 1; i < cntRange; i++) {

            //如果当前数和前一个数相同
            //用于记录相同的数的个数
            int cnt = 1;
            while (i < cntRange && nums[i] == nums[i - 1]) {
                cnt++;
                i++;
            }
            //需要向前覆盖的数数量

            int offset = cnt - 2;

            if (cnt > 2 && offset > 0) {

                //更新数组的长度

                //数字向前移动
                for (int j = i; j < cntRange; j++) {

                    //数组向前移动的位数
                    nums[j - offset] = nums[j];
                }
                cntRange = cntRange - offset;
                //i坐标也要向前移动
                i = i - offset;
            }


        }

        return cntRange;
    }

    public static void main(String[] args) {
        RemoveDuplicatesFromSortedArrayii removeDuplicatesFromSortedArrayii = new RemoveDuplicatesFromSortedArrayii();
        int[] nums = new int[]{1, 1, 1, 2, 2, 2, 3, 3};
        int i = removeDuplicatesFromSortedArrayii.removeDuplicates(nums);
        System.out.println();
        System.out.println(i);
        for (int j = 0; j < i; j++) {
            System.out.print(nums[j] + " ");
        }
    }
}
